package com.vs.controller;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.vs.model.UploadForm;
import com.vs.util.Constants;

public class UploadAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("execute called");
		UploadForm uploadForm = (UploadForm) form;
		FileOutputStream outputStream = null;
		String projectPath = Constants.UPLOAD_PATH + "/" + uploadForm.getProjectId();
		createRootFolderIfNotExists(projectPath);
		
		String filePath = projectPath + "/"+uploadForm.getProjectId()+"_"
				+ uploadForm.getUploadFile().getFileName();

		System.out.println("filePath=" + filePath);
		try {
			outputStream = new FileOutputStream(new File(filePath));
			outputStream.write(uploadForm.getUploadFile().getFileData());
		} catch (Exception e) {
			ActionErrors errors = new ActionErrors();
			errors.add("uploadedFile", new ActionMessage("errors.file.save",
					uploadForm.getUploadFile().getFileName()));
			saveErrors(request, errors);
		} finally {
			if (outputStream != null)
				outputStream.close();
		}

		System.out.println("" + getErrors(request));
		if (getErrors(request) == null || getErrors(request).size() == 0) {
			///uploadForm.setFileName(uploadForm.getUploadedFile().getFileName());
			return mapping.findForward("success");
		} else
			return mapping.getInputForward();
	}
	
	private void createRootFolderIfNotExists(String file)
	{
		File rootFolder = new File(file);
		if(!rootFolder.isDirectory())
		{
			System.out.println("creating project root folder ="+file);
			rootFolder.mkdir();
		}
	}
	
	private void listDocuments(String projectId)
	{
		String projectPath = Constants.UPLOAD_PATH + "/" + projectId;
		File rootFolder = new File(projectPath);
		String docs [] = rootFolder.list();
		for(int i=0;i<docs.length;i++)
		{
			String actualFile = docs[i];
			String displayFile = actualFile.substring(actualFile.indexOf("_")+1,actualFile.length());
			System.out.println("actualFile="+actualFile+";displayFile="+displayFile);
		}
	}
	
	public static void main(String args[])
	{
		UploadAction a = new UploadAction();
		a.listDocuments("4");
	}
}
